package com.bsuir.avareader.dal;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class BookmarksDbAdapter {

	public static final String KEY_ROWID = "_id";
	private Context context;
	private SQLiteDatabase db;
	private AvaReaderDbHelper dbHelper;

	public BookmarksDbAdapter(Context context) {
		this.context = context;
	}

	public BookmarksDbAdapter open() throws SQLException {
		dbHelper = new AvaReaderDbHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public long createBookmark(String name, double ratio) {
		ContentValues values = createContentValues(name, ratio);

		return db.insert(AvaReaderDbHelper.TABLE_BOOKMARKS, null, values);
	}

	public boolean deleteBookmark(long rowId) {
		return db.delete(AvaReaderDbHelper.TABLE_BOOKMARKS, KEY_ROWID + "="
				+ rowId, null) > 0;
	}

	public Cursor fetchAllBookmarks() {
		return db.query(AvaReaderDbHelper.TABLE_BOOKMARKS, new String[] {
				KEY_ROWID, AvaReaderDbHelper.NAME, AvaReaderDbHelper.RATIO },
				null, null, null, null, null);
	}

	public Cursor fetchAllBookmarksForBook(String name) {
		return db.query(AvaReaderDbHelper.TABLE_BOOKMARKS, new String[] {
				KEY_ROWID, AvaReaderDbHelper.NAME, AvaReaderDbHelper.RATIO },
				AvaReaderDbHelper.NAME + "=" + name, null, null, null, null);
	}

	public Cursor fetchBookmark(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, AvaReaderDbHelper.TABLE_BOOKMARKS,
				new String[] { KEY_ROWID, AvaReaderDbHelper.NAME,
						AvaReaderDbHelper.RATIO }, KEY_ROWID + "=" + rowId,
				null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	private ContentValues createContentValues(String name, double ratio) {
		ContentValues values = new ContentValues();
		values.put(AvaReaderDbHelper.NAME, name);
		values.put(AvaReaderDbHelper.RATIO, ratio);
		return values;
	}

}